<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件号码" prop="cardno">
        <el-input
            v-model="queryParams.cardno"
            placeholder="证件号码"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="primary" v-if="false" icon="Plus" @click="handleAdd" v-hasPermi="['by:post:add']">添加
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="postList">
      <el-table-column label="姓名" align="center" prop="name"/>
      <el-table-column label="证件号码" align="center" prop="cardno"/>
      <el-table-column label="院校" align="center" prop="school"/>
      <el-table-column label="专业" align="center" prop="subject"/>
      <el-table-column label="联系方式" align="center" prop="mobile"/>
      <el-table-column label="订单数量" align="center" prop="ordercount"/>
      <el-table-column label="评价数量" align="center" prop="discount"/>
      <el-table-column label="小时/单价" align="center" prop="hprice"/>
      <el-table-column label="分钟/单价" align="center" prop="mprice"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="showStatus"/>
      <el-table-column label="创建时间" align="center" prop="addtime" width="180"/>
      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['by:post:edit']">更新</el-button>
          <el-button v-if="scope.row.status == 1" link type="primary" @click="upStatus(scope.row,'2')">不显示</el-button>
          <el-button v-if="scope.row.status != '1'" link type="primary" @click="upStatus(scope.row,'1')">显示</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />


    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图片" prop="postName">
          <el-upload
              class="avatar-uploader"
              action="https://www.zhaobangyang.cn:1000/prod-api/wx/bs/saveImg"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="姓名"/>
        </el-form-item>
        <el-form-item label="证件号码" prop="cardno">
          <el-input v-model="form.cardno" placeholder="证件号码"/>
        </el-form-item>
        <el-form-item label="院校" prop="school">
          <el-input v-model="form.school" disabled placeholder="院校"/>
        </el-form-item>
        <el-form-item label="选择院校" prop="schoolId">
          <el-select v-model="form.schoolDetail" @change="loadSchoolSel" placeholder="选择院校(为了小程序端的选择用)" style="width:100%;">
            <el-option
                v-for="dict in schoollist"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="subject">
          <el-input v-model="form.subject" placeholder="专业"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="form.mobile" placeholder="联系方式"/>
        </el-form-item>
        <el-form-item label="特长" prop="sp">
          <el-input v-model="form.sp" placeholder="特长"/>
        </el-form-item>
        <el-form-item label="小时/单价" prop="hprice">
          <el-input v-model="form.hprice" placeholder="小时/单价"/>
        </el-form-item>
        <el-form-item label="分钟/单价" prop="mprice">
          <el-input v-model="form.mprice" placeholder="分钟/单价"/>
        </el-form-item>

        <el-form-item label="简介" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="简介"/>
        </el-form-item>
        <el-form-item label="开设科目" prop="subject">


          <view class="list-content" v-for="(i, k) in subjectlist" :key="k">
            <el-checkbox
                class="checkbox"
                v-model="i.flag"
                @change="handleCheckedCitiesChange(i)"
            ></el-checkbox>
            {{i.name}}
          </view>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import {listBs, getBs, updateBs, imgsave, mangSubjectAndBsid } from "@/api/bydll/bs";
import { getAllSubjectNoTop } from "@/api/bydll/classify";
import { upBsStatus } from "@/api/bydll/bs";
import { getAllSchool } from "@/api/bydll/school";


const {proxy} = getCurrentInstance();
const {sys_normal_disable} = proxy.useDict("sys_normal_disable");
const showSearch = ref(true);
const postList = ref([]);
const open = ref(false);
const title = ref("");
const loading = ref(true);
const total = ref(0);
const ids = ref([]);
const imageUrl = ref('');
const subjectlist = ref([]);
const schoollist = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined
  },
  rules: {
    name: [{required: true, message: "院校名称不能为空", trigger: "blur"}]
  }
});
const {queryParams, form, rules} = toRefs(data);

const handleAvatarSuccess = (response, uploadFile) => {
  // console.log(JSON.stringify(uploadFile.raw));
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  loadImgToBase(uploadFile.raw);
}

function showStatus(row, column){
  if(row.status === '1'){
    return "显示";
  }else if(row.status === '0'){
    return "申请帮手";
  }else{
    return "不显示";
  }
}

function loadSchoolSel(e){
  // console.log(JSON.stringify(e));
  form.value.schoolId = e;
}

function upStatus(row,status){
  let param = {"id":row.id,"status":status};
  upBsStatus(param).then((resp) => {
    getList();
  })
}



function handleCheckedCitiesChange(i){
  // 进行操作当前的数据、添加或者删除
  let param = {"subjectid":i.id,"bsid":ids.value};
  mangSubjectAndBsid(param).then((resp) => {
    console.log(JSON.stringify(resp));
  })
}



function loadImgToBase(blob){
  getImageBase64(blob).then((base64) => {
    //执行需要的操作，比如显示图片等等
    addFile(base64);
  })
}


function addFile(base){
  var param = {"baseStr":base};
  imgsave(param).then(response => {
    form.value.img = response.msg;
  });
}


// 将文件转成base64
function getImageBase64(blob) {
  return new Promise((resolve,reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => {
      const base64 = reader.result;
      resolve(base64);
    }
    reader.onerror = error => reject(error);
  });
}







function getBase64(file) {
  return new Promise((resolve, reject) =>{
    let reader = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function() {
      imgResult = reader.result;
    };
    reader.onerror = function(error) {
      reject(error);
    };
    reader.onloadend = function() {
      resolve(imgResult);
    };
  });
}




const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage('图片仅支持jpg格式的图片！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于2MB!')
    return false
  }
  return true
}


function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


function handleDelete(row) {
  const schoolIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除院校？').then(function () {
    return delSchool(schoolIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}


function getList() {
  loading.value = true;
  listBs(queryParams.value).then(response => {
    postList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        // console.log(JSON.stringify(form.value));
        updateBs(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        /*addBs(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });*/
      }
    }
  });
}

function handleUpdate(row) {
  reset();
  const postId = row.id || ids.value;
  ids.value = row.id;
  // 进行加载开设科目
  loadKm(postId);
  getBs(postId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "帮手管理";
    imageUrl.value = response.data.img;
  });
}

function kmflag(flag){
  if(flag == 1){
    return true;
  }else{
    return false;
  }
}

function loadKm(bsid){
  // subjectlist.value = [];
  var param = {"bsid":bsid};
  // console.log(param);
  getAllSubjectNoTop(param).then(resp => {
    // console.log(JSON.stringify(resp.data));
    subjectlist.value = resp.data;
  })
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加院校";
}

/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    remark: undefined
  };
  proxy.resetForm("postRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

function getSchoolSel(){
  getAllSchool().then(resp => {
    // console.log(JSON.stringify(resp.data));
    schoollist.value = resp.data;
  });
}


getSchoolSel();
getList();
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.avatar{
  width: 100px;
  height: 100px;
}
</style>